#include <iostream>
#include <string>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <cstring>

using namespace std;

#define PORT 8888
#define BUF_SIZE 1024

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }

    sockaddr_in server_addr{};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  // 默认连接本地

    if (connect(sockfd, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect");
        return 1;
    }

    cout << "Enter your nickname: ";
    string nickname;
    getline(cin, nickname);
    send(sockfd, nickname.c_str(), nickname.size(), 0);

    cout << "Connected to server. Type your message:" << endl;

    fd_set read_fds;

    while (true) {
        FD_ZERO(&read_fds);
        FD_SET(0, &read_fds);         // 标准输入
        FD_SET(sockfd, &read_fds);    // socket 输入
        int max_fd = max(0, sockfd) + 1;

        int activity = select(max_fd, &read_fds, nullptr, nullptr, nullptr);
        if (activity < 0) continue;

        // 用户输入
        if (FD_ISSET(0, &read_fds)) {
            string msg;
            getline(cin, msg);
            if (msg.empty()) continue;
            send(sockfd, msg.c_str(), msg.size(), 0);
            if (msg == "/quit") break;
        }

        // 服务器消息
        if (FD_ISSET(sockfd, &read_fds)) {
            char buf[BUF_SIZE];
            int len = recv(sockfd, buf, sizeof(buf) - 1, 0);
            if (len <= 0) {
                cout << "[Server disconnected]" << endl;
                break;
            }
            buf[len] = '\0';
            cout << buf << flush;
        }
    }

    close(sockfd);
    return 0;
}

